import { useRequest } from 'ahooks';
import { Button, Form, Input } from 'antd';
import { useTranslation } from 'react-i18next';

import messageBox from '@/utils/messageBox';

import styles from '../index.module.scss';
import { register, RegisterProps } from '../service';

interface RegisterType {
  switchActiveStatus: () => void;
}

const Register: React.FC<RegisterType> = props => {
  const [form] = Form.useForm();
  const { t } = useTranslation() as { t: (a: string) => string };
  const { switchActiveStatus } = props;

  const { run: runRegister, loading } = useRequest(
    async (params: RegisterProps = form.getFieldsValue()) => {
      await register(params).then(() => {
        messageBox.success({ content: 'Register Successfully' });
      });
      form.resetFields();
      switchActiveStatus();
    },
    { manual: true },
  );

  return (
    <div className={styles.registerCard}>
      <h1 className="text-3xl font-bold mb-14">{t('signUp')}</h1>
      <Form form={form} onFinish={runRegister}>
        <Form.Item
          name="username"
          rules={[
            { required: true, message: t('usernameRequire') },
            { min: 6, max: 18, message: t('usernameLength') },
          ]}
        >
          <Input placeholder={t('usernamePlaceholder')} className="w-72 h-10" />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[
            { required: true, message: t('passwordRequire') },
            { min: 6, max: 18, message: t('passwordLength') },
          ]}
        >
          <Input.Password placeholder={t('passwordPlaceholder')} className="w-72 h-10" />
        </Form.Item>
        <Form.Item
          name="confirmPassword"
          rules={[
            { required: true, message: t('passwordRequire') },
            { min: 6, max: 18, message: t('passwordLength') },
            {
              validator: (_, value) =>
                value === form.getFieldValue('password') ? Promise.resolve() : Promise.reject(),
              message: t('passwordConfirm'),
            },
          ]}
        >
          <Input.Password
            onPressEnter={() => runRegister()}
            placeholder={t('passwordPlaceholder')}
            className="w-72 h-10"
          />
        </Form.Item>
      </Form>
      <Button className="submitBtn" loading={loading} onClick={() => form.submit()}>
        {t('SIGNUP')}
      </Button>
    </div>
  );
};

export default Register;
